import React, { Component } from 'react';
import './form.less';
import moment from 'moment';
import BreadcrumbCustom from '../common/BreadcrumbCustom';
import CollectionCreateForm from './CustomizedForm';
import FormTable from './FormTable';
import AddModal from './addModalVisible';
import { Button, message, Modal, Tooltip, Icon } from 'antd';
import fetchRequest from '../../fetch/fetchRequest';

// 找到对应元素的索引
function catchIndex(arr, id) { // 获取INDEX
    let index = 0;
    arr.forEach(function (ar, ind) {
        if (ar.id === id) {
            index = ind;
        }
    });
    return index;
}
// eslint-disable-next-line no-extend-native
Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1,                 //月份 
        "d+": this.getDate(),                    //日 
        "h+": this.getHours(),                   //小时 
        "m+": this.getMinutes(),                 //分 
        "s+": this.getSeconds(),                 //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds()             //毫秒 
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
}
export default class UForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            userName: '',
            timeRange: '',
            visible: false, // 新建窗口隐藏
            dataSource: [],
            selectedRowKeys: [],
            tableRowKey: 0,
            isUpdate: false,
            loading: true,
            formData: { username: '', orderPrincipal: '', orderCommission: '', orderRemarks: '' },
            settlement: false
        };
    }
    // 获取订单列表
    getUsersList() {
        fetchRequest.fetchR('orders', 'GET')
            .then((response) => {
                if (response.status) {
                    message.error(response.message);
                } else {
                    if (response.length !== 0) {
                        response.sort(function (a, b) {
                            return Date.parse(b.orderTime) - Date.parse(a.orderTime);//时间降序
                        });
                        // 向数据添加标记属性
                        response.map(item => item.tag = false)
                        
                        // 按时间分类排序
                        const firstDay = response[0].orderTime.split(' ')[0];
                        const endDay = response[response.length - 1].orderTime.split(' ')[0];
                        // 获得时间间隔数
                        const tempDate = Date.parse(firstDay) - Date.parse(endDay)
                        const iDays = Math.floor(tempDate / (24 * 3600 * 1000));

                        let currenDay = firstDay;
                        for (let i = 0; i < iDays + 1; i++) {
                            let index = 0;
                            // eslint-disable-next-line no-loop-func
                            response.forEach((item => {
                                let orderTime = item.orderTime.split(' ')[0];
                                if (orderTime === currenDay) {
                                    item.index = index + 1;
                                    index++;
                                }
                            }))
                            currenDay = new Date(Date.parse(currenDay) - 1000 * 60 * 60 * 24).format("yyyy/MM/dd");
                        }
                    }

                    this.setState({
                        dataSource: response,
                        loading: false
                    })
                }
            }).catch((err) => {  //网络请求失败返回的数据
                console.log(err)
                message.error('数据获取失败')
            });
    }

    // 渲染
    componentDidMount() {
        this.getUsersList();
    }
    //接受新建表单数据
    saveFormRef = (form) => {
        this.form = form;
    };
    // 取消
    handleCancel = () => {
        this.setState({ visible: false });
    };
    // 单个删除
    onDelete = (id) => {
        fetchRequest.fetchR(`orders/${id}`, 'delete')
            .then(res => {
                message.success('删除成功!');
                this.getUsersList();
            }).catch(err => {
                message.error('删除失败!');
            })
    };
    // 点击修改
    editClick = (key) => {
        const { dataSource } = this.state;
        const index = catchIndex(dataSource, key);
        this.setState({
            visible: true,
            tableRowKey: key,
            formData: dataSource[index]
        });
    };
    // 更新修改
    handleUpdate = () => {
        // 获取当前登录的用户
        const form = this.form;
        const { dataSource, tableRowKey } = this.state;
        
        form.validateFields((err, values) => {
            if (err) {
                return;
            }

            // 订单号,时间,操作人,其他不变
            const index = catchIndex(dataSource, tableRowKey);
            values.orderNumber = dataSource[index].orderNumber;
            values.orderTime = dataSource[index].orderTime;
            values.operator = dataSource[index].operator;
            values.others = dataSource[index].others;

            fetchRequest.fetchR(`orders/${tableRowKey}`, 'put', values)
                .then(res => {
                    message.success('更新成功！')
                    this.getUsersList();
                    this.setState({
                        visible: false
                    });
                    form.resetFields();
                }).catch(err => {
                    message.error('更新失败!');
                    this.setState({
                        visible: false
                    });
                    form.resetFields();
                })

            values.id = tableRowKey;
        });
    };

    // 添加订单的相关操作
    addModal = () => {
        this.setState({
            addModalVisible: true
        })
    }
    // 取消添加
    addCancel = () => {
        const form = this.addForm;
        form.resetFields();
        this.setState({
            addModalVisible: false
        })
    };
    // 添加
    addOk = () => {
        // 获取当前登录的用户
        let currentUser = JSON.parse(localStorage.getItem('mspa_user'));
        const form = this.addForm;
        const { selectedUser, billId, noSettlementBill } = this.state;
        form.validateFields((err, values) => {
            if (err) {
                return;
            }

            // 添加订单
            values.orderTime = moment().format("YYYY/MM/DD HH:mm:ss");
            values.operator = currentUser.username;
            fetchRequest.fetchR('orders', 'post', values)
                .then(res => {
                    message.success('添加成功！');
                    this.getUsersList();
                    this.setState({
                        addModalVisible: false
                    });
                    form.resetFields();
                }).catch(err => {
                    message.error('添加失败!');
                    this.setState({
                        addModalVisible: false
                    });
                    form.resetFields();
                })

            if (selectedUser.todayFirstOrderTime === null || selectedUser.todayFirstOrderTime !== moment().format("YYYY/MM/DD")) {
                const body = {
                    username: selectedUser.username,
                    password: selectedUser.password,
                    firstCommission: values.orderCommission,
                    firstPrincipal: values.orderPrincipal,
                    todayFirstOrderTime: moment().format("YYYY/MM/DD"),
                }
                // 更新用户的每一天的第一次佣金
                fetchRequest.fetchR(`users/firstMoney/${selectedUser.id}`, 'put', body)
                    .then(res => {
                        this.setState({
                            addModalVisible: false
                        });
                    }).catch(err => {
                        this.setState({
                            addModalVisible: false
                        });
                    })
            }

            // 向账单中加入今天的未结算订单
            const today = moment().format("YYYY/MM/DD");
            if (noSettlementBill.indexOf(today) === -1) {
                if (noSettlementBill === '') {
                    // 更新未结算账单
                    const body = {
                        username: values.username,
                        settlementDay: today + ';'
                    };
                    fetchRequest.fetchR(`settlement/${billId}`, 'put', body)
                        .then(res => {
                        }).catch(err => {
                        })
                } else {
                    noSettlementBill.split(";").push(today)
                    // 更新未结算账单
                    const body = {
                        username: values.username,
                        settlementDay: noSettlementBill
                    };
                    fetchRequest.fetchR(`settlement/${billId}`, 'put', body)
                        .then(res => {
                        }).catch(err => {
                        })
                }
            }
        });
    };
    // 接受新建表单数据
    saveAddFormRef = (form) => {
        this.addForm = form;
    };
    // 添加的订单的时所选中的用户
    selectedUser = (value) => {
        this.setState({
            selectedUser: value
        })
        this.getSettlement(value.username)
    }

    // 添加账单操作
    // 通过用户名获得订单的id，以便做账单更新
    getSettlement(username) {
        fetchRequest.fetchR(`settlement/${username}`, 'get')
            .then(res => {
                if (res.error === undefined) {
                    this.setState({
                        billId: res.id,
                        noSettlementBill: res.settlementDay
                    })
                }
            }).catch(err => {
                message.error('数据获取失败!');
            })
    }

    // 重置查询
    clearFilters = () => {
        // this.formTable.handleReset();
        // console.log(this.formTable)
    }

    onRef = (ref) => {
        this.child = ref
    }
    // 选择的订单
    selectedOrders = (selectedRowKeys) => {
        this.setState({ selectedRowKeys });
        if (selectedRowKeys.length === 0) {
            this.setState({
                settlement: false
            })
        }
    }
    // 选中订单结算
    settlement = () => {
        const { selectedRowKeys, dataSource } = this.state;
        if (selectedRowKeys.length === 0) {
            Modal.info({ content: '请选择至少一个订单', okText: '确定' })
        } else {
            let benjin = 0;
            let yongjin = 0;
            dataSource.forEach(item => {
                if (selectedRowKeys.indexOf(item.id) > -1) {
                    benjin += item.orderPrincipal;
                    yongjin += item.orderCommission;
                }
            })
            this.setState({
                benjinSettlement: benjin,
                yongjinSettlement: yongjin,
                settlement: true
            })
        }
    }
    // 清空选择
    start = () => {
        this.setState({
            selectedRowKeys: [],
            settlement: false
        });
    }

    // 选中订单结账
    jiezhang = (text) => {
        const { selectedRowKeys, dataSource } = this.state;
        if (selectedRowKeys.length === 0) {
            Modal.info({ content: '请选择至少一个订单', okText: '确定' })
        } else {
            dataSource.forEach(item => {
                if (selectedRowKeys.indexOf(item.id) > -1) {
                    item.others = '已结账'    
                    fetchRequest.fetchR(`orders/${item.id}`, 'put', item)
                    .then(res => {
                        console.log('结账成功')                   
                    }).catch(err => {
                        console.log(err)
                    })
                }
            })
            this.getUsersList() // 重新获取列表
        }
    }
    // 选中订单标记为未结账
    weijiezhang = (text) => {
        const { selectedRowKeys, dataSource } = this.state;
        if (selectedRowKeys.length === 0) {
            Modal.info({ content: '请选择至少一个订单', okText: '确定' })
        } else {
            dataSource.forEach(item => {
                if (selectedRowKeys.indexOf(item.id) > -1) {
                    item.others = '未结账'    
                    fetchRequest.fetchR(`orders/${item.id}`, 'put', item)
                    .then(res => {
                        console.log('修改成功')                   
                    }).catch(err => {
                        console.log(err)
                    })
                }
            })
            this.getUsersList() // 重新获取列表
        }
    }
    

    render() {
        const { dataSource, visible, loading, formData, addModalVisible, selectedRowKeys, benjinSettlement, yongjinSettlement, settlement } = this.state;

        const today = moment().format("YYYY/MM/DD");
        let count = 0;
        let benjin = 0;
        let yongjin = 0;

        let aCount = 0;
        let aBenjin = 0;
        let aYongjin = 0;

        let bCount = 0;
        let bBenjin = 0;
        let bYongjin = 0;

        dataSource.forEach(item => {
            let orderTime = item.orderTime.split(' ')[0];
            if (orderTime === today) {
                count = count + 1;
                benjin += item.orderPrincipal;
                yongjin += item.orderCommission;

                // 记录两个管理员账号的今日订单情况
                if (item.operator === 'admin') {
                    aCount = aCount + 1;
                    aBenjin += item.orderPrincipal;
                    aYongjin += item.orderCommission;
                } else if (item.operator === 'admin_1'){
                    bCount = bCount + 1;
                    bBenjin += item.orderPrincipal;
                    bYongjin += item.orderCommission;
                }
            }
        })

        // 选中的订单数
        const hasSelected = selectedRowKeys.length > 0;
        return (
            <div>
                <BreadcrumbCustom paths={['首页', '订单管理']} />
                <div className='formBody'>
                    <Button type='primary' onClick={this.addModal}>添加订单</Button>&nbsp;
                    {/* <Button onClick={this.clearFilters}>重置查询</Button> */}
                    <Button
                        type="primary"
                        onClick={this.start}
                        disabled={!hasSelected}
                    >
                        清空选择
                    </Button>&nbsp;
                    <Button onClick={this.settlement} >结算</Button>
                    <span style={{ marginLeft: 8 }}>
                        {hasSelected ? <span>已选 <span style={{ fontWeight: 'bold' }}>{selectedRowKeys.length} </span>项；</span> : ''}
                        {settlement ? <span>所选订单本金共：<span style={{ fontWeight: 'bold' }}>{parseFloat(benjinSettlement).toFixed(2)}</span>元；
                        佣金共：<span style={{ fontWeight: 'bold' }}>{parseFloat(yongjinSettlement).toFixed(2)}</span>元</span> : ''}
                    </span>
                    <span style={{ float: 'right' }}>
                        今日订单共：<span style={{ fontWeight: 'bold' }}>{count}</span>单；
                        本金：<span style={{ fontWeight: 'bold' }}>{parseFloat(benjin).toFixed(2)}</span>元；
                        佣金：<span style={{ fontWeight: 'bold' }}>{parseFloat(yongjin).toFixed(2)}</span>元
                    </span><br/>
                    <span style={{ float: 'right' }}> 
                        admin账号：                      
                        今日订单共：<span style={{ fontWeight: 'bold' }}>{aCount}</span>单；
                        本金：<span style={{ fontWeight: 'bold' }}>{parseFloat(aBenjin).toFixed(2)}</span>元；
                        佣金：<span style={{ fontWeight: 'bold' }}>{parseFloat(aYongjin).toFixed(2)}</span>元
                    </span><br/>
                    <span style={{ float: 'right' }}>                         
                        admin_1账号&nbsp;<Tooltip title="admin_1的订单字体为蓝色"><Icon type="question-circle-o" /></Tooltip>：                      
                        今日订单共：<span style={{ fontWeight: 'bold' }}>{bCount}</span>单；
                        本金：<span style={{ fontWeight: 'bold' }}>{parseFloat(bBenjin).toFixed(2)}</span>元；
                        佣金：<span style={{ fontWeight: 'bold' }}>{parseFloat(bYongjin).toFixed(2)}</span>元
                    </span>
                    <Button type='primary' onClick={this.jiezhang} >结账</Button> &nbsp;
                    <Button onClick={this.weijiezhang} >未结账</Button>
                    {/* 订单列表展示 */}
                    <FormTable
                        dataSource={dataSource}
                        onDelete={this.onDelete}
                        editClick={this.editClick}
                        loading={loading}
                        onRef={this.onRef}
                        selectedOrders={this.selectedOrders}
                        selectedRowKeys={selectedRowKeys}
                    />
                    {/* 修改订单 */}
                    <CollectionCreateForm
                        ref={this.saveFormRef}
                        visible={visible}
                        formData={formData}
                        onCancel={this.handleCancel}
                        onCreate={this.handleUpdate}
                        title="修改信息"
                        okText="更新" />
                    {/* 添加订单 */}
                    <AddModal
                        ref={this.saveAddFormRef}
                        dataSource={dataSource}
                        addModalVisible={addModalVisible}
                        addCancel={this.addCancel}
                        selectedUser={this.selectedUser}
                        addOk={this.addOk} />
                </div>
            </div>
        )
    }
}